﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace dms.SingleR
{
    public class RTCHub : Hub
    {
        /// <summary>
        /// 连接的用户
        /// </summary>
        public readonly static Dictionary<string, string> userConnections = new Dictionary<string, string>();

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <remarks>张三登录</remarks>
        /// <example>connection.invoke("Login","张三"）</example>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task Login(string name)
        {
            // 当前连接id
            string connid = Context.ConnectionId;
            if (!userConnections.ContainsKey(name))
            {
                userConnections.Add(name, connid);
            }
            else
            {
                userConnections[name] = connid;
            }
            // 通知客户端加入完成
            await Clients.Client(connid).SendAsync("onLogin", name);
        }

        /// <summary>
        /// 邀请他人
        /// </summary>
        /// <remarks>张三邀请李四</remarks>
        /// <example>connection.invoke("Offer","李四",offer）</example>
        /// <param name="name">他人名称</param>
        /// <param name="offer">邀请函</param>
        /// <returns></returns>
        public async Task<MyJsonResult> Offer(string name, object offer)
        {
            MyJsonResult result = new MyJsonResult();
            // 当前连接用户
            string me = this.current;
            if (me == null)
            {
                result.Success = false;
                result.Msg = "当前用户不存在";
                return result;
            }
            // 他人连接id
            string otherConnid = null;
            userConnections.TryGetValue(name, out otherConnid);
            if (otherConnid == null)
            {
                result.Success = false;
                result.Msg = $"{name}不在线";
                return result;
            }
            // 向某用户发送邀请函
            await Clients.Client(otherConnid).SendAsync("onOffer", me, offer);

            result.Success = true;
            return result;
        }

        /// <summary>
        /// 应答他人
        /// </summary>
        /// <remarks>李四应答张三</remarks>
        /// <example>connection.invoke("Answer","张三",answer）</example>
        /// <param name="name">他人名称</param>
        /// <param name="answer">应答函</param>
        /// <returns></returns>
        public async Task<MyJsonResult> Answer(string name, object answer)
        {
            MyJsonResult result = new MyJsonResult();
            // 当前连接用户
            string me = this.current;
            if (me == null)
            {
                result.Success = false;
                result.Msg = "当前用户不存在";
                return result;
            }
            // 他人连接id
            string otherConnid = null;
            userConnections.TryGetValue(name, out otherConnid);
            if (otherConnid == null)
            {
                result.Success = false;
                result.Msg = $"{name}不在线";
                return result;
            }
            // 向某用户发送应答函
            await Clients.Client(otherConnid).SendAsync("onAnswer", me, answer);

            result.Success = true;
            return result;
        }

        /// <summary>
        /// ICE候选发送到他人
        /// </summary>
        /// <remarks>李四候选信息发送张三</remarks>
        /// <example>connection.invoke("Candidate","张三",candidate）</example>
        /// <param name="name">他人名称</param>
        /// <param name="candidate">候选人信息</param>
        /// <returns></returns>
        public async Task<MyJsonResult> Candidate(string name, object candidate)
        {
            MyJsonResult result = new MyJsonResult();
            // 当前连接用户
            string me = this.current;
            if (me == null)
            {
                result.Success = false;
                result.Msg = "当前用户不存在";
                return result;
            }
            // 他人连接id
            string otherConnid = null;
            userConnections.TryGetValue(name, out otherConnid);
            if (otherConnid == null)
            {
                result.Success = false;
                result.Msg = $"{name}不在线";
                return result;
            }
            // 向某用户发送应答函
            await Clients.Client(otherConnid).SendAsync("onCandidate", me, candidate);

            result.Success = true;
            return result;
        }

        /// <summary>
        /// 本人下线并通知他人
        /// </summary>
        /// <remarks>张三下线，通知李四</remarks>
        /// <example>connection.invoke("Leave","李四"）</example>
        /// <param name="name">他人名称</param>
        /// <returns></returns>
        public async Task<MyJsonResult> Leave(string name)
        {
            MyJsonResult result = new MyJsonResult();
            // 当前连接用户
            string me = this.current;
            if (me == null)
            {
                result.Success = false;
                result.Msg = "当前用户不存在";
                return result;
            }
            // 他人连接id
            string otherConnid = null;
            userConnections.TryGetValue(name,out otherConnid);
            if (otherConnid == null)
            {
                result.Success = false;
                result.Msg = $"{name}不在线";
                return result;
            }
            // 向某用户发送应答函
            await Clients.Client(otherConnid).SendAsync("onLeave", me);
            result.Success = true;
            return result;
        }

        /// <summary>
        /// 断开连接则从集合中移除用户
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception exception)
        {
            // 当前连接用户
            string me = this.current;
            if (!string.IsNullOrWhiteSpace(me))
            {
                if (userConnections.ContainsKey(me))
                {
                    userConnections.Remove(me);
                }
            }
            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 根据连接获取用户名
        /// </summary>
        private string current
        {
            get
            {
                string connid = Context.ConnectionId;
                if (!userConnections.ContainsValue(connid))
                {
                    return null;
                }
                // 获取当前用户名
                return userConnections.FirstOrDefault(a => a.Value == connid).Key;
            }
        }
    }
}
